package com.lan.app.service.impl;

import com.lan.app.dao.TbDao;
import com.lan.app.repository.Tb;
import com.lan.app.repository.Tp;
import com.lan.app.dao.TpDao;
import com.lan.app.service.ITbService;
import com.lan.support.page.Page;
import com.lan.support.page.PageHelper;
import com.lan.support.response.ex.Ex;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TbService implements ITbService {

    @Resource
    private TbDao tbDao;

    @Resource
    private TpDao tpDao;

    @Override
    public Integer save(Tb Tb) {
        Date curDate = new Date();
        Tb.setIsDel(1);
        Tb.setState(1);
        Tb.setCreateTime(curDate);
        Tb.setUpdateTime(curDate);
        tbDao.save(Tb);
        Integer id = Tb.getId();
        return id;
    }

    @Override
    public int del(Integer id) {
        int result = tbDao.del(id);
        return result;
    }

    @Override
    public int modifyDel(Integer id) {
        int result = tbDao.modifyDel(id, 0, new Date());
        return result;
    }

    public int updateById(Tb Tb) {
        if (Tb.getId() == null) {
            throw Ex.build("ID 不能为空");
        }
        int result = tbDao.updateById(Tb);
        return result;
    }

    @Override
    public Tb get(Integer id) {
        Tb Tb = tbDao.findById(id);
        return Tb;
    }

    @Override
    public Page<Tb> page(PageHelper helper, Tb Tb) {
        int count = tbDao.countByPage(Tb, helper.getPage());
        Page<Tb> page = new Page<>(helper, count);
        if (count == 0) {
            page.setContent(null);
        } else {
            List<Tb> list = tbDao.findByPage(Tb, helper.getPage());
            page.setContent(list);
        }
        return page;
    }

    @Override
    public List<Tb> getList(boolean isTp) {
        List<Tb> list = tbDao.getALL();
        if(isTp){
            fill(list);
        }
        return list;
    }


    private void fill(List<Tb> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<Integer> tbIdList = list.stream().map(v -> v.getId()).collect(Collectors.toList());
        List<Tp> tpList = tpDao.findList(tbIdList);
        if (CollectionUtils.isNotEmpty(tpList)) {
            Map<Integer, List<Tp>> tpMap = tpList.stream().collect(Collectors.groupingBy(v -> v.getTbId()));
            for (int i = 0; i < list.size(); i++) {
                Tb Tb = list.get(i);
                List<Tp> tps = tpMap.get(Tb.getId());
                Tb.setList(tps);
            }
        }
    }

}